package admin.data;

import models.IdCountModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class IdCountData {
	private static Objectify ofy;
	private static boolean isRegisted = false;

	public static void init() {
		if (!isRegisted) {
			try {
				ObjectifyService.register(IdCountModel.class);
				isRegisted = true;
			} catch (Exception e) {
				System.out.println("Error Register !");
				e.printStackTrace();
			}
			ofy = ObjectifyService.begin();
		}
	}

	public static void insert(IdCountModel obj) {
		ofy.put(obj);
	}

	public static void delete(IdCountModel obj) {
		ofy.delete(obj);
	}

	public static String getIdByType(String type) {
		init();
		IdCountModel obj = new IdCountModel();
		boolean hasNo = false;
		try {
			obj = ofy.get(new Key<IdCountModel>(IdCountModel.class, type));
			if (obj != null && obj.getCurrentCount() > 0) {
				obj.setCurrentCount(obj.getCurrentCount() + 1);
				insert(obj);
				return obj.getCurrentCount().toString();
			} else {
				hasNo = true;
			}
		} catch (Exception e) {
			hasNo = true;
		}
		if (hasNo) {
			obj = new IdCountModel();
			obj.setTypeId(type);
			int id = 0;
			if (type.equals("1") || type.equals("3") || type.equals("5")
					|| type.equals("6")) {
				id = 1000;
			} else if (type.equals("2")) {
				id = 10000;
			} else if (type.equals("4")) {
				id = 100000;
			}
			obj.setCurrentCount((long) id);
			insert(obj);
		}
		return obj.getCurrentCount().toString();
	}

}
